<template>
  <div class="option-wrapper">
    <div class="option-main">
      <a-form layout="vertical" :model="formState" ref="formRef" :rules="rules">
        <!-- 客户基础信息 -->
        <div class="option-column">
          <div class="column-title">客户基础信息</div>
          <div class="column-content-a">
            <a-row :gutter="24">
              <a-col :span="12">
                <a-form-item label="客户" name="customer_name">
                  <a-select
                    v-model:value="formState.customer_name"
                    placeholder="请选择客户"
                    show-search
                    @change="handleChoose"
                  >
                    <a-select-option
                      v-for="item in customerOptions"
                      :key="item.value || item.id"
                      :value="item.value"
                    >
                      {{ item.label || item.name }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="客户编号">
                  <a-input
                    :disabled="true"
                    v-model:value="formState.customer_no"
                    placeholder="自动填充"
                  />
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="12">
                <a-form-item label="客户分类" name="customer_type_name">
                  <a-input
                    :disabled="true"
                    v-model:value="formState.customer_type_name"
                    placeholder="自动填充"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="状态" name="status">
                  <a-input
                    :disabled="true"
                    v-model:value="formState.status"
                    placeholder="自动填充"
                  />
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="12">
                <a-form-item label="所在地区">
                  <a-input
                    :disabled="true"
                    v-model:value="formState.address"
                    placeholder="自动填充"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="所属经销商">
                  <a-input
                    :disabled="true"
                    v-model:value="formState.dealer_name"
                    placeholder="自动填充"
                  />
                </a-form-item>
              </a-col>
            </a-row>
          </div>
        </div>

        <!-- 联系人信息 -->
        <div class="option-column">
          <div class="column-title">联系人信息</div>
          <div class="column-content-a">
            <a-row :gutter="24">
              <a-col :span="12">
                <a-form-item label="联系人姓名" name="real_name">
                  <a-input
                    v-model:value="formState.real_name"
                    placeholder="请输入联系人姓名"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="账号" name="login_name">
                  <a-input
                    :disabled="isEdit"
                    v-model:value="formState.login_name"
                    placeholder="建议使用手机号"
                  />
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="12">
                <a-form-item label="启用状态">
                  <a-select
                    v-model:value="formState.enabled"
                    placeholder="请选择启用状态"
                  >
                    <a-select-option :value="true">启用</a-select-option>
                    <a-select-option :value="false">禁用</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="手机号" name="mobile">
                  <a-input
                    v-model:value="formState.mobile"
                    placeholder="请输入手机号"
                  />
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="12">
                <a-form-item label="初始密码" name="login_password">
                  <a-input-password
                    v-model:value="formState.login_password"
                    placeholder="请输入初始密码"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="备注">
                  <a-input
                    v-model:value="formState.remark"
                    placeholder="请输入备注信息"
                  />
                </a-form-item>
              </a-col>
            </a-row>
          </div>
        </div>
        <div class="option-footer">
          <a-button class="opt-btn" @click="resetForm">取消</a-button>
          <a-button class="opt-btn" type="primary" @click="submitForm"
            >保存</a-button
          >
        </div>
      </a-form>
    </div>
  </div>
</template>
<script setup>
import { ref, computed, onMounted, watch } from "vue";
import { useRoute } from "vue-router";
import { validateMobile, validatePassword } from "@/utils/validate";
import API from "@/api/administrator";
import SAPI from "@/api/system";
import OAPI from "@/api/operation";
import { getCityName } from "@/utils/city.ts";
import { message } from "ant-design-vue";
import router from "@/routers";
const route = useRoute();
//获取当前url参数
const query = computed(() => route.query);
const customerOptions = ref([]);
const dealerOptions = ref([]);
const zoneoList = ref([]);
const formState = ref({
  // 客户基础信息
  customer_name: "", // 对应customer_id
  customer_no: "", // 对应customer.no
  customer_type_name: "", // 对应customer_type_id
  status: "", // 对应customer_status_id
  address: "", // 对应customer.address
  dealer_name: "", // 对应dealer_id
  // 账号基础信息
  real_name: "",
  login_name: "",
  login_password: "",
  enabled: null,
  mobile: "",
  remark: "",
});
const rules = ref({
  customer_name: [
    {
      required: true,
      message: "请选择客户",
      trigger: "blur",
    },
  ],

  real_name: [
    {
      required: true,
      message: "请输入联系人姓名",
      trigger: "blur",
    },
  ],
  login_name: [
    {
      required: true,
      message: "请输入账号",
      trigger: "blur",
    },
  ],
  login_password: [
    {
      required: true,
      validator: validatePassword,
      trigger: "blur",
    },
  ],
  mobile: [
    {
      required: false,
      validator: validateMobile,
      trigger: "blur",
    },
  ],
});
const customer_id = ref("");
const user_id = ref("");
const formRef = ref(null);
const submitForm = async () => {
  formRef.value.validate().then(async () => {
    // 按照新的CreateCustomerWithUserArgs格式组织数据结构
    if (query.value.id) {
      let userData = {
        user_id: user_id.value,

        real_name: formState.value.real_name,
        login_name: formState.value.login_name,
        login_password: formState.value.login_password,
        enabled: formState.value.enabled,
        mobile: formState.value.mobile,
        remark: formState.value.remark,
      };
      const userInfo = await API.UserUpdate(userData);
      let submitData = {
        customer_id: customer_id.value,
        user_id: user_id.value,
      };
      const res = await API.CustomeruserUpdate(submitData);
      if (res) {
        formRef.value.resetFields();
        //提示编辑成功
        message.success("编辑成功");
        //后退
        router.go(-1);
      }
    } else {
      let userData = {
        real_name: formState.value.real_name,
        login_name: formState.value.login_name,
        login_password: formState.value.login_password,
        enabled: formState.value.enabled,
        mobile: formState.value.mobile,
        remark: formState.value.remark,
      };
      const userInfo = await API.UserCreate(userData);
      user_id.value = userInfo.user_id;
      let submitData = {
        customer_id: customer_id.value,
        user_id: user_id.value,
      };
      const res = await API.CustomerUserCreate(submitData);
      console.log(res);
      if (res) {
        formRef.value.resetFields();
        //提示新增成功
        message.success("新增成功");
        //后退
        router.go(-1);
      }
    }
  });
};
const resetForm = () => {
  formState.value = {
    // 客户基础信息
    customer_name: "",
    customer_no: "",
    customer_type: undefined,
    status: undefined,
    city_id: [],
    dealer: undefined,
    // 账号基础信息
    real_name: "",
    login_name: "",
    login_password: "",
    enabled: null,
    mobile: "",
    remark: "",
    roleIds: [],
  };
  router.go(-1);
};

// 获取经销商选项
const getDealerOptions = async () => {
  try {
    const res = await OAPI.DealerOptions({});
    console.log("经销商选项数据:", res);
    dealerOptions.value = res || [];
  } catch (error) {
    console.error("获取经销商选项失败:", error);
  }
};
// 获取客户选项
const getCustomerOptions = async () => {
  try {
    const res = await API.CustomerOptions({});
    customerOptions.value = res || [];
  } catch (error) {
    console.error("获取客户选项失败:", error);
  }
};
const getData = async () => {
  let params = {
    customer_user_id: query.value.id,
  };
  const res = await API.CustomeruserFetchModel(params);

  // 根据新的API返回结构处理数据 - 客户信息直接在 data 字段中
  if (res) {
    const customerData = res?.customer;
    const userData = res?.user; // 用户信息直接在 user 字段中
    user_id.value = userData?.user_id; // 用户ID

    formState.value = {
      // 客户基础信息 - 基于返回的客户数据
      customer_name: customerData?.name || "", // 使用客户名称
      customer_no: customerData?.no || "",
      customer_type_name:
        classOptions.value.find(
          (item) => item.value == customerData?.customer_type_id
        )?.text || "",
      status:
        statusOptions.value.find(
          (item) => item.value == customerData?.customer_status_id
        )?.text || "",
      address: getCityName(zoneoList.value, customerData?.city_id) || "",
      dealer_name: customerData?.dealer_name || "",
      // 其他信息 - 基于客户数据
      real_name: userData?.real_name || "", // 联系人姓名，如果 contacts 为 null 则为空
      login_name: userData?.login_name || "", // 使用客户名称作为登录名
      login_password: userData?.login_password, // 编辑时不回显密码
      enabled: userData?.enabled ?? true,
      mobile: userData?.mobile || "", // 手机号，如果 contacts 为 null 则为空
      remark: userData?.remark || "", // 备注信息，如果 contacts 为 null 则为空
    };
  }
};

const handleChoose = async (item) => {
  console.log("选择了：", item);
  customer_id.value = item;
  let params = {
    customer_id: item,
  };
  const res = await API.CustomerFetchModel(params);
  const customerData = res;
  formState.value = {
    ...formState.value,
    // 客户基础信息 - 基于返回的客户数据
    customer_name: customerData?.name || "", // 使用客户名称
    customer_no: customerData?.no || "",
    customer_type_name:
      classOptions.value.find(
        (item) => item.value == customerData?.customer_type_id
      )?.text || "",
    status:
      statusOptions.value.find(
        (item) => item.value == customerData?.customer_status_id
      )?.text || "",
    address: getCityName(zoneoList.value, customerData?.city_id) || "",
    dealer_name: customerData?.dealer_name || "",
  };
};
const statusOptions = ref([]);
const getStatusOptions = async () => {
  const res = await API.CustomerStatusOptions({});
  statusOptions.value = res;
};
const classOptions = ref([]);
const getTypeOptions = async () => {
  const res = await API.CustomerTypeOptions({});
  classOptions.value = res;
};
const getZoneData = async () => {
  const res = await SAPI.CityCityTree();
  zoneoList.value = res;
};
const isEdit = ref(false);
onMounted(async () => {
  // 加载下拉选项数据
  await getCustomerOptions();
  await getStatusOptions();
  await getTypeOptions();
  await getDealerOptions();
  await getZoneData();

  // 如果是编辑模式，加载用户数据
  if (query.value.id) {
    await getData();
    isEdit.value = true;
  } else {
    isEdit.value = false;
  }
});
</script>

<style scoped>
.option-wrapper {
  padding: 20px;
}

.option-main {
  background: #fff;
  border-radius: 8px;
  padding: 24px;
}

.option-column {
  margin-bottom: 32px;
}

.option-column:last-child {
  margin-bottom: 0;
}

.column-title {
  font-size: 16px;
  font-weight: 600;
  color: #262626;
  margin-bottom: 20px;
  padding-left: 12px;
}

.column-content {
  padding: 0 12px;
}

.content-item {
  margin-bottom: 16px;
}

.option-footer {
  display: flex;
  justify-content: center;
  gap: 16px;
  margin-top: 32px;
  padding-top: 24px;
  border-top: 1px solid #f0f0f0;
}

.opt-btn {
  min-width: 100px;
  height: 40px;
}
</style>
